package net.keebook.webapp.bean;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.TimeZone;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import org.apache.log4j.Logger;

import net.keebook.webapp.dao.KeeBookDao;
import net.keebook.webapp.dao.SettingDao;
import net.keebook.webapp.dao.ShareRequestDao;
import net.keebook.webapp.dao.UserDao;
import net.keebook.webapp.entity.KeeBook;
import net.keebook.webapp.entity.ShareRequest;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.AccessRight;
import net.keebook.webapp.util.DateUtil;
import net.keebook.webapp.util.Mail;
import net.keebook.webapp.util.MessageBundle;
import net.keebook.webapp.util.Messages;
import net.keebook.webapp.util.SettingId;


@ManagedBean
@RequestScoped
public class AddShareRequestBean {
	private String email;
	private String message;
	private String accessRight;
	private SessionModel sessionModel;
	
	@Inject
	private ShareRequestDao shareRequestDao;
	@Inject
	private SettingDao settingDao;
	@Inject 
	private KeeBookDao keeBookDao;
	@Inject 
	private UserDao userDao;
	
	@PostConstruct
	public void init() throws IOException {
		setSessionModel(SessionModel.getInstance(FacesContext.getCurrentInstance()));
		
		if (!getKeeBookDao().getKeeBookAccess(getSessionModel(), AccessRight.OWNER)) {
			Logger.getLogger(this.getClass()).warn("Forbidden access to bean from userId="+getSessionModel().getUserId());
			FacesContext.getCurrentInstance().getExternalContext().redirect("403.xhtml");
			return;
		}
		
		setAccessRight(AccessRight.READ_ONLY.name());
		setMessage("");
	}
	
	public void sendInvitation() throws IOException {
		if (!getKeeBookDao().getKeeBookAccess(getSessionModel(), AccessRight.OWNER)) {
			Logger.getLogger(this.getClass()).warn("Forbidden access to bean from userId="+getSessionModel().getUserId());
			FacesContext.getCurrentInstance().getExternalContext().redirect("403.xhtml");
			return;
		}
		
		KeeBook keeBook = getKeeBookDao().get(getSessionModel().getKeeBookId());
		User user = getUserDao().get(getSessionModel().getUserId());
		
		if (!user.getConfirmed()) return;
		if ("".equals(user.getName())) return;
		
		TimeZone systemTimeZone = TimeZone.getTimeZone(getSettingDao().get(SettingId.SYSTEM_TIMEZONE).getValue());
		
		ShareRequest sr = new ShareRequest();
		sr.setAccessRight(AccessRight.valueOf(getAccessRight()));
		sr.setCreationDate(DateUtil.getUtcTimestamp(systemTimeZone));
		sr.setEmail(getEmail());
		sr.setInvitingUser(user);
		sr.setKeeBook(keeBook);
		getShareRequestDao().store(sr);
		
		String url = getSettingDao().get(SettingId.PUBLIC_URL).getValue() + "/services/join/" + sr.getExposableId();
		String message;
		if ("".equals(getMessage())) {
			message = MessageBundle.get().getString("mail.shareMailWithoutMessage");
			message = MessageFormat.format(message, user.getName(), keeBook.getName(), url);
		} else {
			message = MessageBundle.get().getString("mail.shareMailWithMessage");
			message = MessageFormat.format(message, user.getName(), keeBook.getName(), url, getMessage());
		}
		
		sr.setMessage(message);
		getShareRequestDao().update(sr);
		
		String subject = MessageBundle.get().getString("mail.shareMailSubject");
		subject = MessageFormat.format(subject, user.getName());
		
		Mail mail = new Mail(
				getSettingDao().get(SettingId.SMTP_HOST).getValue(), 
				getSettingDao().get(SettingId.SMTP_PORT).getLong().intValue(),
				getSettingDao().get(SettingId.SMTP_AUTH).getBoolean(),
				getSettingDao().get(SettingId.SMTP_USERNAME).getValue(),
				getSettingDao().get(SettingId.SMTP_PASSWORD).getValue(),
				getSettingDao().get(SettingId.SMTP_ENABLE).getBoolean());
		try {
			mail.sendMail(
				getSettingDao().get(SettingId.SMTP_SENDER_ADDRESS).getValue(),
				"KeeBook",
				getEmail(),
				null,
				subject,
				message);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		FacesContext.getCurrentInstance().getExternalContext().redirect("share.xhtml?msg="+Messages.SHARE_REQUEST_SENT);
	}
	public ShareRequestDao getShareRequestDao() {
		return shareRequestDao;
	}
	public void setShareRequestDao(ShareRequestDao shareRequestDao) {
		this.shareRequestDao = shareRequestDao;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}

	public String getAccessRight() {
		return accessRight;
	}

	public void setAccessRight(String accessRight) {
		this.accessRight = accessRight;
	}

	public SettingDao getSettingDao() {
		return settingDao;
	}

	public void setSettingDao(SettingDao settingDao) {
		this.settingDao = settingDao;
	}

	public KeeBookDao getKeeBookDao() {
		return keeBookDao;
	}

	public void setKeeBookDao(KeeBookDao keeBookDao) {
		this.keeBookDao = keeBookDao;
	}

	public SessionModel getSessionModel() {
		return sessionModel;
	}

	public void setSessionModel(SessionModel sessionModel) {
		this.sessionModel = sessionModel;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}
